package com.yjyw.tiexie.common.net;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
public class ThreadPoolManger {
    /**
     * 要求 一个app运行期间只有一个实例
     */

    private static volatile ThreadPoolManger manger;

    private static ThreadPoolExecutor poolExecutor;
    private List<Runnable> list;

    private ThreadPoolManger() {
        if (list==null){
            list=new ArrayList<>();
        }
    }

    /**
     * 开启线程池
     *
     * @return
     */
    public static ThreadPoolManger getInstance() {
        if (manger == null) {
            synchronized (ThreadPoolManger.class) {
                if (manger == null) {
                    manger = new ThreadPoolManger();
                    //创建线程池，cpu的核心数，系统开启的核心数
                    int cpuNum = Runtime.getRuntime().availableProcessors();
                    poolExecutor = new ThreadPoolExecutor(cpuNum + 1, cpuNum * 2 + 1,
                            1, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<Runnable>(cpuNum * 2 + 1));
                }
            }
        }
        return manger;
    }

    public void addTask(Runnable runnable) {
        if (runnable != null) {
            list.add(runnable);
            //执行添加过来的任务
            poolExecutor.execute(runnable);

        }

    }

    public boolean removeTask(Runnable runnable) {
        if (runnable != null) {
            return poolExecutor.remove(runnable);
        }
        return false;
    }

    public boolean removeTaskAll() {
           if ( list.size()==0){
               return false;
           }
        for (int i = 0; i <list.size() ; i++) {
            poolExecutor.remove(list.get(i));
        }
        return true;
    }
}
